/*
 * @Description: 本单位、跨单位申请 表格
 * @Author: Rfan
 * @Date: 2022-03-21 19:01:08
 * @LastEditTime: 2023-02-03 13:50:31
 */

import { useEffect, useMemo, useState } from 'react';
import classNames from 'classnames/bind';
import { Button, Space, Table } from 'antd';
import type { FC, MouseEvent } from 'react';
import type { TableRowSelection } from 'antd/lib/table/interface';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useRightApplyContext } from '../contexts/RightApplyContext';
import type { IPageQuery } from '@/interfaces/global';
import { appState } from '@/store/mobx';

import styles from '../styles/list.module.scss';
import ApproveDialog from './dialogs/ApproveDialog';
import { IStartAuditProps } from '@/api/workFlow/task';

const cx = classNames.bind(styles);

const { Column } = Table;

export type SortPaneProps = {
  title?: string;
  data?: any;
};

const ApplyTable: FC<SortPaneProps> = ({ title, data }) => {
  console.log('borrow apply table:', data);
  const formatMessage = useFormatMessage();
  const {
    approveList,
    setArcList,
    getApproveList,
    approveDialog,
    startTaskFunc,
    showApproveDialog
  } = useRightApplyContext();
  // 列表选中的条目
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  // 列表加载状态
  const [loading, setLoading] = useState(false);
  /* 可视 */
  const [applyVisible, setApplyVisible] = useState(false);
  // 全部条目数
  const [total, setTotal] = useState(0);
  // 请求参数
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10
  });

  /**
   * @description: 参数变更，如切换页面请求列表
   */
  useEffect(() => {
    setLoading(true);
    getApproveList(listQuery)
      .then((res: any) => {
        console.log('back', res);
        setTotal(res?.totalCount);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [listQuery]);

  /**
   * @description: 切换页码触发
   * @param {number} page 选中的页码
   * @param {number} pageSize 请求的条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state: any) => {
      return {
        ...state,
        pageNo: page,
        pageSize
      };
    });
  };

  /**
   * @description : 案卷表格选中相关
   * @param {number} selectedKeys
   * @return {*}
   */
  const onSelectChange = (selectedKeys: number[]): void => {
    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(selectedKeys[0]) < 0) {
      setSelectedRowKeys(selectedKeys);
    }
  };
  const rowSelection: TableRowSelection<any> = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange
  };

  /**
   * @description: 案卷列表选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(record.id) < 0) {
      setSelectedRowKeys([record.id]);
      setArcList(record.id);
    }
  };

  /**
   * @description: 点击查看按钮展示弹窗
   * @param {MouseEvent} evt 点击事件
   * @param {any} item 条目信息
   * @return {*}
   */
  const showDetailModal = (evt: MouseEvent, item: any): void => {
    evt.stopPropagation();
    setApplyVisible(true);
    showApproveDialog(item.id);
  };

  /**
   * @description: 点击提交
   * @param {any} item 条目信息
   */
  const submitAudit = (item: any): void => {
    const params: IStartAuditProps = {
      businessKey: item.applyFormNo,
      identity: appState.userInfo.id,
      modelType: 'QUAN_XIAN_FLOW'
    };
    startTaskFunc(params);
  };

  return (
    <div className={cx('apply-table')}>
      <Table
        dataSource={approveList || []}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        onRow={(record) => ({
          onClick: () => {
            selectRow(record);
          }
        })}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />
        <Column title="申请单号" dataIndex="id" key="code" align="center" />
        <Column title="申请单名称" dataIndex="name" key="name" align="center" />
        <Column title="全宗" dataIndex="fondsName" key="fondsName" align="center" />
        <Column title="状态" dataIndex="status" key="status" align="center" />
        <Column title="利用目的" dataIndex="purpose" key="purpose" align="center" />
        <Column title="实体利用申请" dataIndex="useTypeEntity" key="useTypeEntity" align="center" />
        <Column
          title="电子利用申请"
          dataIndex="useTypeElectronicRights"
          key="useTypeElectronicRights"
          align="center"
        />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                onClick={(evt) => {
                  showDetailModal(evt, record);
                }}
              >
                查看
              </Button>
              {record.status === 1 && (
                <Button
                  type="link"
                  onClick={(evt) => {
                    evt.stopPropagation();
                    submitAudit(record);
                  }}
                >
                  提交
                </Button>
              )}
            </Space>
          )}
        />
      </Table>
      {useMemo(
        () =>
          JSON.stringify(approveDialog) !== '{}' && (
            <ApproveDialog
              visible={applyVisible}
              data={approveDialog}
              onClose={() => {
                setApplyVisible(false);
              }}
            />
          ),
        [applyVisible, approveDialog]
      )}
    </div>
  );
};

export default ApplyTable;
